<template>
  <bui-page-layout ref="pageLayout" :is-z-paging="false" @popupClose="pClose">
    <view class="withdraw-type">
      <text class="t">收款方式选择</text>
      <text class="p" @click="openRoutePath('pages/withdraw/records')">提现记录</text>
    </view>
    <view class="withdraw-mode-item" @click="onWithdrawMode">
      <template v-if="isPayLoad">
        <view class="hd">
          <view class="icon">
            <image v-if="payModeIndexItem" :src="'/static/image/icon-'+imageSytle(1,payModeIndexItem)+'.png'" :style="imageSytle(2,payModeIndexItem)" />
          </view>
          <view class="name">{{ payModeIndexItem?.type === 1?'微信账户':payModeIndexItem?.type === 2?'支付宝':'银行卡'}}</view>
        </view>
        <view class="card-info">
          <text class="name u-line-1" v-if="payModeIndexItem?.type === 1 || payModeIndexItem?.type === 2">{{ payModeIndexItem?.accountNo}}({{ payModeIndexItem?.name}})</text>
          <text class="name u-line-1" v-if="payModeIndexItem?.type === 3">{{payModeIndexItem?.bankName }}({{payModeIndexItem?.accountNo }})</text>
          <text class="branch u-line-1" v-if="payModeIndexItem?.type === 3">{{payModeIndexItem?.branchBank }}</text>
        </view>
        <view class="arrow">
          <image src="/static/image/icon-arrow-right.png" class="icon"></image>
        </view>
      </template>
    </view>
    <view class="withdraw-type">
      <text class="t">提取金额</text>
    </view>
    <view class="withdraw-mode-item">
      <view class="keyboard">
        <text class="cny">￥</text>
        <view class="input" @click="onKeyboard" :class="{placeholder:!keyboardValue}">
          <text class="text"> {{ filterNumber(keyboardValue) || '0.00' }}</text>
        </view>
      </view>
    </view>
    <view class="withdraw-bottom-info">当前可提现金额<text class="a">{{ filterNumber(withdrawInfo.balance+'') || 0 }}</text>元；提现手续费<text class="a">{{ filterDot(serviceFeeRatio) }}</text>元 (1%)</view>
    <b-button :loading="buttonLoading" @change="saveWithdraw" style="margin:30rpx 30rpx 0">
      <text class="button_t">申请提现</text>
    </b-button>
    <template v-slot:popup>
      <view class="withdraw-popup" v-if="!isPassword">
        <view class="title-hd u-border-bottom">
          <text class="t">选择收款方式</text>
        </view>
        <view class="pay-mode-popup-wp">
          <view v-for="(item,index) in payModeList" :key="index">
            <view class="pay-mode-popup-item" @click="onPayModeItem(index,item)">
              <view class="pay-mode">
                <view class="icon">
                  <image :src="'/static/image/icon-'+imageSytle(1,item)+'.png'" :style="imageSytle(2,item)" />
                </view>
                <text class="name">{{ item?.type === 1?'微信账户':item?.type === 2?'支付宝':'银行卡'}}</text>
              </view>
              <view class="card-info">
                <text class="name u-line-1" v-if="item.type === 1 || item.type === 2">{{ item?.accountNo}}({{ item?.name}})</text>
                <text class="name u-line-1" v-if="item.type === 3">{{item.bankName }}({{item ?.accountNo }})</text>
                <text class="branch u-line-1" v-if="item.type === 3">{{item.branchBank }}</text>
              </view>
              <view class="pay-radio" v-if="payModeIndex === index">
                <image src="/static/image/icon-pay-radio.png" class="icon" />
              </view>
            </view>
            <view class="line">
              <view class="u-border-top"></view>
            </view>
          </view>
          <view class="cancel" @click="onCancel">
            <text class="t">取消</text>
          </view>
        </view>
      </view>
      <view class="withdraw-password" v-else>
        <view class="title">
          <text class="t">提现密码</text>
        </view>
        <u--input ref="inpuRef" :focus="true" type="password" placeholder="请输入提现密码" style="padding: 20rpx 15rpx;" v-model="withdarwSaveInfo.payPass" />
        <b-button :loading="buttonLoading" @change="saveWithdraw" style="margin-top: 30rpx;">
          <text class="button_t">申请提现</text>
        </b-button>
      </view>
    </template>

    <up-keyboard mode="number" @close="closeOnClickOverlay" :safeAreaInsetBottom="true" :tooltip="false" @change="valChange" @backspace="backspace" :show="keyboardShow"></up-keyboard>
  </bui-page-layout>
</template>
<script setup>
import { ref, nextTick, computed, watch } from "vue";
import { onShow } from "@dcloudio/uni-app";
import md5Libs from "@/lib/md5";
var buttonLoading = ref(false);
const keyboardValue = ref(""); // 输入框的值
const keyboardShow = ref(false); // 是否显示键盘
const isPayLoad = ref(true);
const isPassword = ref(false);
const pageLayout = ref(null);
const inpuRef = ref(null);
let payModeIndex = ref(0);
let payModeList = ref([]);
let withdrawInfo = ref({});
let payModeIndexItem = ref();
payModeIndexItem = computed(() => {
  var _payItem = payModeList.value[payModeIndex.value];
  withdarwSaveInfo.value.accountId = _payItem?.id;
  return _payItem;
});
let withdarwSaveInfo = ref({
  accountId: 0,
  amount: 0,
  payPass: "",
});
let serviceFeeRatio = ref(0);
serviceFeeRatio = computed(() => {
  return (
    withdrawInfo.value.serviceFeeRatio *
      parseFloat(filterNumber(keyboardValue.value)) *
      0.01 || 0
  );
});
const openRoutePath = (path) => {
  uni.$u.route({
    url: path,
  });
};
// 保存提现/m/withdraw/apply/first
const withdrawFirst = () => {
  uni.$request
    .service({
      url: "/m/withdraw/apply/first",
      method: "POST",
      data: {},
    })
    .then((res) => {
      withdrawInfo.value = res;
    });
};
onShow(() => {
  withdrawFirst();
});
const getPaymentAccountList = (callback) => {
  uni.$request
    .service({
      url: "/m/receive/account/list",
      method: "GET",
      data: {},
    })
    .then((res) => {
      payModeList.value = res;
      if (!res.length) {
        pageLayout.value.uModalShow({
          title: "温馨提示",
          content: "你还没有添加收款方式，无法提现",
          confirmText: "去绑定",
          complete: async () => {
            uni.$u.route({
              url: "pages/payment/index",
            });
          },
        });
      } else {
        pageLayout.value.uModalClose();
      }
      callback && callback();
    });
};
// 申请提现
const saveWithdraw = () => {
  if (uni.$u.test.isEmpty(withdarwSaveInfo.value.accountId)) {
    uni.$u.toast("收款方式没有选择");
    return;
  }
  if (uni.$u.test.isEmpty(withdarwSaveInfo.value.amount)) {
    uni.$u.toast("提现金额不能为空");
    return;
  }
  if (!withdrawInfo.value.isSetPayPass) {
    uni.$u.toast("请设置提现密码");
    uni.$u.route({
      url: "pages/setup/withdrawal_password",
    });
    return;
  }
  if (uni.$u.test.isEmpty(withdarwSaveInfo.value.payPass)) {
    if (isPassword.value) {
      uni.$u.toast("交易密码没有输入");
      return;
    }
    isPassword.value = true;
    pageLayout.value.openPopup();
    // inpuRef.value.focus();
    return;
  }
  if (withdarwSaveInfo.value.amount < withdrawInfo.value.minWithdraw) {
    uni.$u.toast("提现金额不能小于" + withdrawInfo.value.minWithdraw);
    return;
  }
  var payPass = md5Libs.md5(withdarwSaveInfo.value.payPass);
  uni.$request
    .service({
      url: "/m/withdraw/apply",
      method: "POST",
      data: {
        ...withdarwSaveInfo.value,
        payPass,
      },
    })
    .then((res) => {
      buttonLoading.value = false;
      // uni.navigateBack({
      //   delta: 1,
      // });
      isPassword.value = false;
      withdarwSaveInfo.value.accountId = 0;
      withdarwSaveInfo.value.amount = 0;
      withdarwSaveInfo.value.payPass = "";
      keyboardValue.value = "";
      pageLayout.value.closePopup();
      uni.$u.route({
        type: "redirectTo",
        url: "pages/withdraw/status",
        params: { type: "success" },
      });
    })
    .catch((error) => {
      buttonLoading.value = false;
      uni.$u.toast(error.message);
      if (error.code === -10000) {
        uni.$u.route({
          url: "pages/setup/withdrawal_password",
        });
      }
    });
};
getPaymentAccountList();
const pClose = () => {
  withdarwSaveInfo.value.payPass = "";
  setTimeout(() => {
    isPassword.value = false;
  }, 300);
};
const onPayModeItem = async (index, item) => {
  payModeIndex.value = index;
  isPayLoad.value = false;
  await nextTick();
  isPayLoad.value = true;
  pageLayout.value.closePopup();
};
const imageSytle = (type, item) => {
  if (type === 1) {
    return item.type === 1 ? "wepay" : item.type === 2 ? "alipay" : "card";
  }
  if (type === 3) {
    return item.name;
  }
  if (type === 2) {
    return item.type == 1
      ? "width: 42rpx;height: 34rpx"
      : item.type == 2
      ? "width: 40rpx;height: 40rpx"
      : "width: 40rpx;height: 30rpx" + ";";
  }
};
const valChange = (val) => {
  // 将每次按键的值拼接到value变量中，注意+=写法
  keyboardValue.value += val;
  console.log(keyboardValue.value);
};
const onKeyboard = () => {
  keyboardShow.value = !keyboardShow.value;
};
const onWithdrawMode = () => {
  pageLayout.value.openPopup();
};

const backspace = () => {
  // 删除value的最后一个字符
  if (keyboardValue.value.length) {
    keyboardValue.value = keyboardValue.value.substr(
      0,
      keyboardValue.value.length - 1
    );
  }
};
const onCancel = () => {
  pageLayout.value.closePopup();
};
const filterNumber = (str) => {
  if (!str) {
    return "0.00";
  }
  // 删除开头的零，除非后面紧跟小数点
  str = str.replace(/^0+(?!\.)/, "");
  // 如果以小数点开头，添加一个零
  if (str.startsWith(".")) {
    str = "0" + str;
  }
  // 处理多个小数点的情况，仅保留第一个小数点
  let pointIndex = str.indexOf(".");
  if (pointIndex !== -1) {
    // 保留第一个小数点及其后的内容，删除后面的小数点
    str =
      str.substring(0, pointIndex + 1) +
      str.substring(pointIndex).replace(/\./g, "");
  }
  // 仅保留第一个小数点和后两位小数
  str = str.replace(/(\.\d\d?)\d*$/, "$1");
  // keyboardValue.value = str;
  return str;
};
// 保留2位小数点
const filterDot = (str) => {
  if (!str) {
    return 0;
  }
  var _value = str + "";
  return _value.replace(/(\.\d\d?)\d*$/, "$1");
};
const closeOnClickOverlay = () => {
  withdarwSaveInfo.value.amount = parseFloat(keyboardValue.value);
  keyboardShow.value = !keyboardShow.value;
};
</script>
<style lang="scss">
page {
  background-color: #f6f6f8;
}
.withdraw-password {
  padding: 20rpx 30rpx;
  .title {
    display: flex;
    justify-content: center;
    padding: 10rpx 0 30rpx 0;
  }
}
.withdraw-type {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .t {
    color: #232f3f;
    font-family: PingFang SC;
    font-size: 32rpx;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }
  .p {
    font-size: 28rpx;
    color: #fe9900;
  }
  padding: 25rpx 40rpx;
}
.withdraw-mode-item {
  display: flex;
  background-color: #fff;
  padding: 30rpx 40rpx;
  .hd {
    display: flex;
    width: 220rpx;
    .icon {
      width: 44rpx;
      height: 44rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 20rpx;
    }
    .name {
      color: #232f3f;
      font-size: 32rpx;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }
  }
  .card-info {
    flex: 1;
    display: flex;
    flex: 1;
    flex-direction: column;
    .name {
      font-size: 32rpx;
      color: #232f3f;
    }
    .branch {
      padding-top: 8rpx;
      font-size: 24rpx;
      color: #9eb0c5;
    }
  }
  .arrow {
    display: flex;
    align-items: center;
    .t {
      font-size: 28rpx;
      color: #9eb0c5;
    }
    .icon {
      width: 32rpx;
      height: 32rpx;
      margin-left: 6rpx;
    }
  }

  .keyboard {
    display: flex;
    flex: 1;
    align-items: center;
    .cny {
      font-size: 48rpx;
      color: #232f3f;
      margin-right: 14rpx;
    }
    .input {
      flex: 1;
      .text {
        font-size: 48rpx;
      }
    }
    .input.placeholder {
      .text {
        color: #e1e1e1;
        font-size: 48rpx;
        font-style: normal;
        font-weight: 500;
        line-height: normal;
      }
    }
  }
}
.withdraw-bottom-info {
  color: #6c7f96;
  padding: 30rpx 40rpx;
  font-family: PingFang SC;
  font-size: 24rpx;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
  .a {
    color: #232f3f;
    padding: 0 2rpx;
  }
}
.withdraw-popup {
  .title-hd {
    display: flex;
    justify-content: center;
    padding: 30rpx 0;
    .t {
      color: rgba(32, 32, 32, 0.3);
    }
  }
  .line {
    margin: 0 40rpx;
  }
  .cancel {
    border-top: 14rpx solid #f3f3f3;
    padding: 28rpx 0;
    display: flex;
    justify-content: center;
    .t {
      font-size: 32rpx;
      color: #fe9900;
    }
  }
  .pay-mode-popup-item {
    display: flex;
    align-items: flex-start;
    padding: 35rpx 0;
    .pay-mode {
      display: flex;
      padding: 0 40rpx 0;
      width: 198rpx;
      .icon {
        width: 44rpx;
        height: 44rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 24rpx;
      }
      .name {
        color: #232f3f;
        font-size: 32rpx;
      }
    }
    .card-info {
      display: flex;
      flex: 1;
      flex-direction: column;
      .name {
        font-size: 32rpx;
        color: #232f3f;
      }
      .branch {
        padding-top: 8rpx;
        font-size: 24rpx;
        color: #9eb0c5;
      }
    }
    .pay-radio {
      width: 40rpx;
      height: 100%;
      margin-right: 40rpx;
      display: flex;
      align-items: center;
      .icon {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
}
.submit {
  background-color: #fe9900;
  display: flex;
  justify-content: center;
  border-radius: 16rpx;
  padding: 22rpx 0;
  margin-top: 30rpx;
  margin: 30rpx 40rpx 0;
  .t {
    font-size: 32rpx;
    color: #fff;
  }
}
</style>
